// packageA/pages/stepChart/stepChart.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as echarts from '../../../ec-canvas/echarts';
const util = require('../../../utils/util');
//去掉尾部的0
const regexp = /(?:\.0*|(\.\d+?)0+)$/;
//图表对象
let Chart = null;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        //传参
        paramObj: null,
        //图表
        ec: {
            //延迟加载
            lazyLoad: true
        },
        //是否显示图表（避免遮挡）
        showChart: true,
        //无数据
        showNoData: true,
        //图表配置
        chartSet: {
            //颜色
            barColor: '#666',
            //轴上标题
            ytitle: '活跃度',
            xtitle: '时间',
        },
        //今日日期
        todayDate: util.timeFormatDay(new Date()),
        //日期选择框
        showDate: false,
        currentDate: new Date().getTime(),
        minDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            } else if (type === 'month') {
                return `${value}月`;
            }
            return value;
        },
        //显示的日期
        currentDateStr: util.timeFormatDay(new Date()),
        //日统计到几天前
        dayNum: 31,
        //今日步数合计
        total: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //设置统计的最小日期
        this.getBeforeDate();

        if (options.paramObj) {
            let paramObj = JSON.parse(options.paramObj);
            console.log('步数传参');
            console.log(paramObj);

            this.setData({
                paramObj: paramObj
            })

            if (paramObj.date) {
                this.setData({
                    currentDateStr: paramObj.date
                })
            }

            if (paramObj.workOverStartTime && paramObj.workOverEndTime) {
                wx.setNavigationBarTitle({
                    title: '加班时段活跃度统计'
                })
            }

            //获取步数数据
            this.getChartData();
        }
    },

    //获取步数数据
    getChartData() {
        //图表组件
        this.echartsComponnet = this.selectComponent('#mychart');
        let pObj = this.data.paramObj;

        this.setData({
            showNoData: false,
            showChart: true
        })

        let param = {
            imei: pObj.imei,
            at: this.data.currentDateStr,
            isNextDay:pObj.isNextDay
        }

        //从加班跳转来的，传参时间
        if (pObj.workOverStartTime && pObj.workOverEndTime) {
            param.workOverStartTime = pObj.workOverStartTime;
            param.workOverEndTime = pObj.workOverEndTime;
        }

        CommonService.stepRecord(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.StepRecordData && res.data.data.result.StepRecordData.length) {
                let result = res.data.data.result.StepRecordData;

                console.log('步数');
                console.log(result);

                //过滤数据-只要今天
                let arr = [];
                result.forEach(item => {
                    //if(item.at.indexOf(this.data.currentDateStr)!=-1){
                    arr.push(item);
                    //}
                });

                if (arr.length) {
                    console.log('今日步数');
                    console.log(arr);

                    //图表数据
                    let xData = [];
                    let yData = [];

                    //当前数减上一条数
                    for (let i = 0; i < arr.length; i++) {
                        xData.push(arr[i].at.substring(11, 16));
                        if (i == 0) {
                            //yData.push(arr[i].step);
                            // yData.push(arr[i].step);
                        } else {
                            if ((arr[i].step - arr[i - 1].step) < 0) {
                                //如果是负数则显示0
                                yData.push(0);
                            } else {
                                yData.push(arr[i].step - arr[i - 1].step);
                            }

                        }
                    }

                    //图表格式
                    let chartData = {
                        xData: xData,
                        yData: [{
                            type: 'bar',
                            data: yData,
                            barWidth: '15px',
                            itemStyle: {
                                normal: {
                                    label: {
                                        show: true,
                                        position: 'right',
                                        color: "#80242d"
                                    },
                                    color: new echarts.graphic.LinearGradient(
                                        1, 0, 0, 0,
                                        [{
                                            offset: 0,
                                            color: '#0385DC'
                                        }, {
                                            offset: 1,
                                            color: '#1f4e79'
                                        }]
                                    )
                                }
                            }
                        }]
                    }

                    console.log('图表数据');
                    console.log(chartData);

                    //求合
                    let total = 0;
                    (chartData.yData[0].data).forEach(item => {
                        total += item;
                    });
                    this.setData({
                        total: total
                    })

                    //判断图表是否第一次绘制
                    this.isHaveChart(Chart, this.echartsComponnet, this.data.chartSet, chartData);

                } else {
                    this.setData({
                        showNoData: true,
                        showChart: false
                    })
                }

            } else {
                this.setData({
                    showNoData: true,
                    showChart: false
                })
            }
        })
    },

    //显示日期选择框
    onShowDate() {
        //加班跳转来的不能切换日期
        if (!this.data.paramObj.workOverStartTime) {
            this.setData({
                showDate: true
            })
            //隐藏图表
            this.hideChart();
        }
    },

    //关闭日期选择框
    onCloseDate() {
        this.setData({
            showDate: false
        })
        //显示图表
        this.showChart();
    },

    //确定日期时
    onConfirmDate(event) {
        this.setData({
            currentDate: event.detail,
            currentDateStr: util.timeFormatDay(event.detail)
        })

        //关闭日期选择框
        this.onCloseDate();

        //获取步数数据
        this.getChartData();
    },

    //设置日统计的最小日期
    getBeforeDate() {
        let rusult = util.countPrevDay(new Date(), this.data.dayNum);
        this.setData({
            minDate: rusult
        });
    },

    //判断图表是否第一次绘制
    isHaveChart(chartObj, componnetObj, setObj, dataObj) {
        if (!chartObj) {
            //如果是第一次绘制，则初始化图表
            this.init_echarts(chartObj, componnetObj, setObj, dataObj);
        } else {
            //更新图表数据
            this.setOption(chartObj, setObj, dataObj);
        }
    },

    //初始化图表
    init_echarts: function (chartObj, componnetObj, setObj, dataObj) {
        componnetObj.init((canvas, width, height) => {
            chartObj = echarts.init(canvas, null, {
                width: width,
                height: height
            });

            this.setOption(chartObj, setObj, dataObj);

            return chartObj;
        });
    },

    //更新图表数据
    setOption: function (chartObj, setObj, dataObj) {
        //清除
        chartObj.clear();
        //设置新数据
        chartObj.setOption(this.getOption(chartObj, setObj, dataObj));
    },

    //指定图表的配置项和数据
    getOption: function (chartObj, setObj, dataObj) {
        //文字颜色
        let fontColor = '#666';

        let option = {
            legend: {
                textStyle: {
                    color: '#666',
                    padding: [0, 30, 0, 0]
                },
                x: 'right',
                y: '-14'
            },
            grid: {
                left: '5%',
                right: '18%',
                top: '10%',
                bottom: '5%',
                containLabel: true,
            },
            xAxis: {
                type: 'value',
                name: setObj.ytitle,
                axisLabel: {
                    color: fontColor,
                    fontSize: 14,
                    interval: 0,
                    rotate: '-20'
                },
                axisLine: {
                    lineStyle: {
                        color: setObj.barColor
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: '#eee'
                    }
                }
            },
            yAxis: {
                type: 'category',
                name: setObj.xtitle,
                axisLabel: {
                    color: fontColor,
                    interval: 0,
                    fontSize: 13,
                    padding: [40, 0, 0, 0]
                },
                axisLine: {
                    lineStyle: {
                        color: setObj.barColor
                    }
                },
                axisTick: {
                    //轴线与数据字段对齐
                    alignWithLabel: false
                },
                data: dataObj.xData,

            },
            series: dataObj.yData
        };

        return option;
    },

    //隐藏图表
    hideChart() {
        this.setData({
            showChart: false
        })
    },

    //显示图表
    showChart() {
        this.setData({
            showChart: true
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
})